package com.huaxi.ddgw.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.huaxi.ddgw.common.exception.GuiguException;
import com.huaxi.ddgw.manager.mapper.SysRoleUserMapper;
import com.huaxi.ddgw.manager.mapper.SysUserMapper;
import com.huaxi.ddgw.manager.service.SysUserService;
import com.huaxi.ddgw.model.dto.system.AssginRoleDto;
import com.huaxi.ddgw.model.dto.system.LoginDto;
import com.huaxi.ddgw.model.dto.system.SysUserDto;
import com.huaxi.ddgw.model.entity.system.SysUser;
import com.huaxi.ddgw.model.vo.common.ResultCodeEnum;
import com.huaxi.ddgw.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {
        //获取验证码
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();
        //根据key查询redis里面的验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key);
        //比较验证码
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
            //不一致 提示错误
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //一致 删除验证码
        redisTemplate.delete("user:validate" + key);
        //获取提交的用户名 LoginDto获取到
        String userName = loginDto.getUserName();
        //根据用户名查sys_user表
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);
        //查不到则用户不存在 返回错误信息
        if (sysUser == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //查到则用户存在
        //获取密码 与数据库中的密码比较
        String database_password = sysUser.getPassword();
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //比较
        if (!input_password.equals(database_password)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //密码一致则登录成功 不一致则登录失败
        //登录成功则生成用户唯一标识token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //把登录成功的用户信息存放在redis
        redisTemplate.opsForValue().set("user:login" + token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);
        //返回LoginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    // 获取登录用户信息
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    //退出登录
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    //用户条件分页查询
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
    //判断用户名不能重复
    String userName = sysUser.getUserName();
    SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
    if (dbSysUser != null) {
        throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
    }
    //输入密码进行加密
    String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
    sysUser.setPassword(md5_password);
    //设置状态值status 1 可用 0 不可用
    sysUser.setStatus(1);
    sysUserMapper.save(sysUser);
    }


    //用户修改
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    //用户删除
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    //用户分配角色
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //根据userId删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());
        //重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        //遍历每个角色id
        for (Long roleId:roleIdList) {
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(), roleId);
        }
    }
}
